package com.ruoyi.web.controller.prevention;
import cn.hutool.core.collection.CollUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.inspection.constant.InspectionConstant;
import com.ruoyi.system.domain.FileManage;
import com.ruoyi.system.domain.vo.PreventionSecurityRiskVO;
import com.ruoyi.system.entity.*;
import com.ruoyi.system.mapper.FileManageMapper;
import com.ruoyi.system.mapper.PreventionCheckTaskMapper;
import com.ruoyi.system.mapper.PreventionHiddenInfoRecordMapper;
import com.ruoyi.system.service.PreventionHiddenInfoRecordService;
import com.ruoyi.system.service.PreventionHiddenRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 隐患录入记录表(PreventionHiddenRegister)表控制层
 * @since 2022-11-22 17:20:34
 */
@RestController
@RequestMapping("/preventionHiddenRegister")
public class PreventionHiddenRegisterController extends BaseController {

    @Resource
    private PreventionHiddenRegisterService preventionHiddenRegisterService;
    @Resource
    private PreventionHiddenInfoRecordService preventionHiddenInfoRecordService;
    @Autowired
    private PreventionHiddenInfoRecordMapper preventionHiddenInfoRecordMapper;
    @Autowired
    private PreventionCheckTaskMapper preventionCheckTaskMapper;
    @Autowired
    private FileManageMapper fileManageMapper;


    /**
     * 分页查询
     * @param preventionHiddenRegister 筛选条件
     * @return 查询结果
     */
    @GetMapping("/listdj")
    public TableDataInfo queryByPagedj(PreventionHiddenRegister preventionHiddenRegister) {
        startPage();
        Long userId = SecurityUtils.getLoginUser().getUserId();
        boolean yhgly = SecurityUtils.getLoginUser().getUser().getRoles().stream().map(SysRole::getRoleKey).distinct().collect(Collectors.toList()).contains("yhgly");
        if (userId != 1 && !yhgly) {
            preventionHiddenRegister.setRegisterId(userId.intValue());
        }
        List<PreventionHiddenRegister> preventionHiddenRegisterList = preventionHiddenRegisterService.queryByPage(preventionHiddenRegister);
        if (!CollectionUtils.isEmpty(preventionHiddenRegisterList)) {
            for (PreventionHiddenRegister register : preventionHiddenRegisterList) {
                List<FileManage> promiseFiles = new ArrayList<>();
                String fileId = register.getHiddenFileId();
                if (StringUtils.isNotEmpty(fileId)) {
                    fileId = fileId.substring(0, fileId.length());
                    if (fileId.contains(",")) {
                        String[] split = fileId.split(",");
                        List<String> id = Arrays.asList(split);
                        if (StringUtils.isNotEmpty(id)){
                            for (String s : id) {
                                FileManage fileManage = fileManageMapper.getById(Integer.valueOf(s));
                                if (!ObjectUtils.isEmpty(fileManage)){
                                    promiseFiles.add(fileManage);
                                }
                            }
                        }
                    } else {
                        FileManage fileManage = fileManageMapper.getById(Integer.valueOf(fileId));
                        if (!ObjectUtils.isEmpty(fileManage)){
                            promiseFiles.add(fileManage);
                        }
                    }
                }
                register.setFileManageList(promiseFiles);
            }
        }
        return getDataTable(preventionHiddenRegisterList);
    }

    @GetMapping("/listsh")
    public TableDataInfo queryByPagesh(PreventionHiddenRegister preventionHiddenRegister) {
        startPage();
        Long userId = SecurityUtils.getLoginUser().getUserId();
        boolean yhgly = SecurityUtils.getLoginUser().getUser().getRoles().stream().map(SysRole::getRoleKey).distinct().collect(Collectors.toList()).contains("yhgly");
        if (userId != 1 && !yhgly) {
            preventionHiddenRegister.setRectificationId(userId.intValue());
        }
        List<PreventionHiddenRegister> preventionHiddenRegisterList = preventionHiddenRegisterService.queryByPage(preventionHiddenRegister);
        if (!CollectionUtils.isEmpty(preventionHiddenRegisterList)) {
            for (PreventionHiddenRegister register : preventionHiddenRegisterList) {
                List<FileManage> promiseFiles = new ArrayList<>();
                String fileId = register.getHiddenFileId();
                if (StringUtils.isNotEmpty(fileId)) {
                    fileId = fileId.substring(0, fileId.length());
                    if (fileId.contains(",")) {
                        String[] split = fileId.split(",");
                        List<String> id = Arrays.asList(split);
                        if (StringUtils.isNotEmpty(id)){
                            for (String s : id) {
                                FileManage fileManage = fileManageMapper.getById(Integer.valueOf(s));
                                if (!ObjectUtils.isEmpty(fileManage)){
                                    promiseFiles.add(fileManage);
                                }
                            }
                        }
                    } else {
                        FileManage fileManage = fileManageMapper.getById(Integer.valueOf(fileId));
                        if (!ObjectUtils.isEmpty(fileManage)){
                            promiseFiles.add(fileManage);
                        }
                    }
                }
                register.setFileManageList(promiseFiles);
            }
        }
        return getDataTable(preventionHiddenRegisterList);
    }

    @GetMapping("/list")
    public TableDataInfo queryByPage(PreventionHiddenRegister preventionHiddenRegister) {
        startPage();
        Long userId = SecurityUtils.getLoginUser().getUserId();
        boolean yhgly = SecurityUtils.getLoginUser().getUser().getRoles().stream().map(SysRole::getRoleKey).distinct().collect(Collectors.toList()).contains("yhgly");
        if (userId != 1 && !yhgly) {
            preventionHiddenRegister.setRectificationUserId(userId.intValue());
            preventionHiddenRegister.setReviewUserId(userId.intValue());
            preventionHiddenRegister.setRegisterUserId(userId.intValue());
        }
        List<PreventionHiddenRegister> preventionHiddenRegisterList = preventionHiddenRegisterService.queryHiddenList(preventionHiddenRegister);
        if (!CollectionUtils.isEmpty(preventionHiddenRegisterList)) {
            for (PreventionHiddenRegister register : preventionHiddenRegisterList) {
                /** 判断隐患是否来自专项检查**/
                String hiddenFrom = register.getHiddenFrom();
                register.setHiddenFrom(null);
                register.setId(register.getHiddenId().intValue());
                if (StringUtils.isNotEmpty(hiddenFrom) &&
                        (InspectionConstant.JIAN_CHA_LAI_YUAN.equals(hiddenFrom) || InspectionConstant.JIAN_CHA_SELF.equals(hiddenFrom))) {
                    continue;
                }

                List<FileManage> promiseFiles = new ArrayList<>();
                String fileId = register.getHiddenFileId();
                if (StringUtils.isNotEmpty(fileId)) {
                    fileId = fileId.substring(0, fileId.length());
                    if (fileId.contains(",")) {
                        String[] split = fileId.split(",");
                        List<String> id = Arrays.asList(split);
                        if (StringUtils.isNotEmpty(id)){
                            for (String s : id) {
                                FileManage fileManage = fileManageMapper.getById(Integer.valueOf(s));
                                if (!ObjectUtils.isEmpty(fileManage)){
                                    promiseFiles.add(fileManage);
                                }
                            }
                        }
                    } else {
                        FileManage fileManage = fileManageMapper.getById(Integer.valueOf(fileId));
                        if (!ObjectUtils.isEmpty(fileManage)){
                            promiseFiles.add(fileManage);
                        }
                    }
                }
                register.setFileManageList(promiseFiles);
            }
        }
        return getDataTable(preventionHiddenRegisterList);
    }

    @GetMapping("/listAll")
    public TableDataInfo listAll(PreventionHiddenRegister preventionHiddenRegister) {
        startPage();
//        Long userId = SecurityUtils.getLoginUser().getUserId();
//        if (userId != 1) {
//            preventionHiddenRegister.setRectificationUserId(userId.intValue());
//            preventionHiddenRegister.setReviewUserId(userId.intValue());
//            preventionHiddenRegister.setRegisterUserId(userId.intValue());
//        }
        List<PreventionHiddenRegister> preventionHiddenRegisterList = preventionHiddenRegisterService.queryByPage(preventionHiddenRegister);
        if (!CollectionUtils.isEmpty(preventionHiddenRegisterList)) {
            for (PreventionHiddenRegister register : preventionHiddenRegisterList) {
                List<FileManage> promiseFiles = new ArrayList<>();
                String fileId = register.getHiddenFileId();
                if (StringUtils.isNotEmpty(fileId)) {
                    fileId = fileId.substring(0, fileId.length());
                    if (fileId.contains(",")) {
                        String[] split = fileId.split(",");
                        List<String> id = Arrays.asList(split);
                        if (StringUtils.isNotEmpty(id)){
                            for (String s : id) {
                                FileManage fileManage = fileManageMapper.getById(Integer.valueOf(s));
                                if (!ObjectUtils.isEmpty(fileManage)){
                                    promiseFiles.add(fileManage);
                                }
                            }
                        }
                    } else {
                        FileManage fileManage = fileManageMapper.getById(Integer.valueOf(fileId));
                        if (!ObjectUtils.isEmpty(fileManage)){
                            promiseFiles.add(fileManage);
                        }
                    }
                }
                register.setFileManageList(promiseFiles);
            }
        }
        return getDataTable(preventionHiddenRegisterList);
    }

    /**
     * 通过主键查询单条数据
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<PreventionHiddenRegister> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(this.preventionHiddenRegisterService.queryById(id));
    }

    /**
     * 新增数据
     * @param preventionHiddenRegister 实体
     * @return 新增结果
     */
    @PostMapping("/create")
    public AjaxResult add(@RequestBody PreventionHiddenRegister preventionHiddenRegister) {
        preventionHiddenRegister.setHiddenProgress("待审核");
        return AjaxResult.success(this.preventionHiddenRegisterService.insert(preventionHiddenRegister));
    }

    /**
     * 编辑数据
     * @param preventionHiddenRegister 实体
     * @return 编辑结果
     */
    @PostMapping("/update")
    public AjaxResult edit(@RequestBody PreventionHiddenRegister preventionHiddenRegister) {
        return AjaxResult.success(this.preventionHiddenRegisterService.update(preventionHiddenRegister));
    }

    /**
     * 删除数据
     * @param id 主键
     * @return 删除是否成功
     */
    @GetMapping("/delete")
    public AjaxResult deleteById(Integer id) {
        return AjaxResult.success(this.preventionHiddenRegisterService.deleteById(id));
    }

    /**
     *  统计分析
     * @return
     */
    @GetMapping("/countHidden")
    public AjaxResult countHidden(Integer deptId,String level) {
        Map<String,List<Map<String, Object>>> map = preventionHiddenRegisterService.countHidden(deptId,level);
        return AjaxResult.success(map);
    }

    /**
     * 隐患审核
     * @return
     */
    @PostMapping("/updateHiddenState")
    public AjaxResult updateHiddenState(@RequestBody PreventionHiddenRegister preventionHiddenRegister) {
        return AjaxResult.success(preventionHiddenRegisterService.updateHiddenState(preventionHiddenRegister));
    }

    /**
     * 流转人
     * @param preventionHiddenRegister 实体
     * @return 编辑结果
     */
    @PostMapping("/updateRectificationUserName")
    public AjaxResult updateRectificationUserName(@RequestBody PreventionHiddenRegister preventionHiddenRegister) {
        this.preventionHiddenRegisterService.updateRectificationUserName(preventionHiddenRegister);
        return AjaxResult.success();
    }

    /**
     * 隐患整改
     * @param preventionHiddenRegister 实体
     * @return 编辑结果
     */
    @PostMapping("/updateRectification")
    public AjaxResult updateRectification(@RequestBody PreventionHiddenRegister preventionHiddenRegister) {
        this.preventionHiddenRegisterService.updateRectification(preventionHiddenRegister);
        return AjaxResult.success();
    }

    /**
     * 复核隐患
     * @param preventionHiddenRegister 实体
     * @return 编辑结果
     */
    @PostMapping("/updateReview")
    public AjaxResult updateReview(@RequestBody PreventionHiddenRegister preventionHiddenRegister) {
        preventionHiddenRegisterService.updateReview(preventionHiddenRegister);
        return AjaxResult.success();
    }


    /**
     * 新增数据_异常
     * @param preventionHiddenRegister 实体
     * @return 新增结果
     */
    @PostMapping("/createAbnormal")
    public AjaxResult createAbnormal(@RequestBody PreventionHiddenRegister preventionHiddenRegister) {
        String dateToStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date());
        preventionHiddenRegister.setHiddenProgress("待审核");
        PreventionHiddenRegister register = this.preventionHiddenRegisterService.insert(preventionHiddenRegister);
        PreventionHiddenInfoRecord preventionHiddenInfoRecord = new PreventionHiddenInfoRecord();
        preventionHiddenInfoRecord.setType(preventionHiddenRegister.getTempType().equals("1") ? 1 : 0);
        if (preventionHiddenRegister.getTempType().equals("1")) {
            preventionHiddenInfoRecord.setHiddenId(register.getId());
            preventionHiddenInfoRecord.setPreventionCheckTaskId(preventionHiddenRegister.getPreventionCheckTaskId());
            preventionHiddenInfoRecord.setPreventionCheckTaskConfigId(preventionHiddenRegister.getPreventionCheckTaskConfigId());
            preventionHiddenInfoRecord.setCreateUser(register.getHiddenCheckUser());
            preventionHiddenInfoRecord.setCreateTime(dateToStr);
            preventionHiddenInfoRecord.setUpdateTime(dateToStr);
        } else {
            preventionHiddenInfoRecord.setHiddenId(register.getId());
            preventionHiddenInfoRecord.setInspectionPlanTaskId(preventionHiddenRegister.getInspectionPlanTaskId());
            preventionHiddenInfoRecord.setInspectionPlanTaskDetailsId(preventionHiddenRegister.getInspectionPlanTaskPointId());
            preventionHiddenInfoRecord.setCreateUser(register.getHiddenCheckUser());
            preventionHiddenInfoRecord.setCreateTime(dateToStr);
            preventionHiddenInfoRecord.setUpdateTime(dateToStr);
        }
        preventionHiddenInfoRecordService.insert(preventionHiddenInfoRecord);
        return AjaxResult.success();
    }


    /**
     * 隐患排查_新增数据_异常
     * @param preventionHiddenRegister 实体
     * @return 新增结果
     */
    @PostMapping("/createHiddenAbnormal")
    public AjaxResult createHiddenAbnormal(@RequestBody PreventionHiddenRegister preventionHiddenRegister) {
        String dateToStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date());
        preventionHiddenRegister.setHiddenProgress("待审核");
        PreventionHiddenRegister register = this.preventionHiddenRegisterService.insert(preventionHiddenRegister);
        PreventionHiddenInfoRecord preventionHiddenInfoRecord = new PreventionHiddenInfoRecord();
        preventionHiddenInfoRecord.setHiddenId(register.getId());
        preventionHiddenInfoRecord.setPreventionCheckTaskId(preventionHiddenRegister.getPreventionCheckTaskId());
        preventionHiddenInfoRecord.setPreventionCheckTaskConfigId(preventionHiddenRegister.getPreventionCheckTaskConfigId());
        preventionHiddenInfoRecord.setCreateUser(register.getHiddenCheckUser());
        preventionHiddenInfoRecord.setCreateTime(dateToStr);
        preventionHiddenInfoRecord.setUpdateTime(dateToStr);
        preventionHiddenInfoRecord.setType(1);
        preventionHiddenInfoRecordService.insert(preventionHiddenInfoRecord);
        return AjaxResult.success();
    }



    @GetMapping("/getHiddenListPage")
    public TableDataInfo getHiddenListPage(PreventionHiddenRegister preventionHiddenRegister) {
        startPage();
        List<PreventionHiddenRegister> preventionHiddenRegisterList = preventionHiddenRegisterService.getHiddenListPage(preventionHiddenRegister);
        if (!CollectionUtils.isEmpty(preventionHiddenRegisterList)) {
            for (PreventionHiddenRegister hiddenRegister : preventionHiddenRegisterList) {
                List<FileManage> hiddenRegisterFiles = new ArrayList<>();
                String fileId = hiddenRegister.getHiddenFileId();
                if (StringUtils.isNotEmpty(fileId)) {
                    fileId = fileId.substring(0, fileId.length() - 1);
                    if (fileId.contains(",")) {
                        String[] split = fileId.split(",");
                        List<String> id = Arrays.asList(split);
                        if (StringUtils.isNotEmpty(id)){
                            for (String s : id) {
                                FileManage fileManage = fileManageMapper.getById(Integer.valueOf(s));
                                if (!ObjectUtils.isEmpty(fileManage)){
                                    hiddenRegisterFiles.add(fileManage);
                                }
                            }
                        }
                    } else {
                        FileManage fileManage = fileManageMapper.getById(Integer.valueOf(fileId));
                        if (!ObjectUtils.isEmpty(fileManage)){
                            hiddenRegisterFiles.add(fileManage);
                        }
                    }
                }
                hiddenRegister.setFileManageList(hiddenRegisterFiles);
            }
        }
        return getDataTable(preventionHiddenRegisterList);
    }

    /**
     * 隐患任务_隐患数值穿透
     * @return 单条数据
     */
    @GetMapping("/queryHiddenTaskId")
    public TableDataInfo queryHiddenTaskId(Integer taskId) {
        startPage();
        List<PreventionHiddenInfoRecord> recordList = this.preventionHiddenInfoRecordMapper.queryHiddenTaskId(taskId);
        if (!CollectionUtils.isEmpty(recordList)){
            for (PreventionHiddenInfoRecord hiddenInfoRecord : recordList) {
                PreventionCheckTask checkTask = preventionCheckTaskMapper.queryById(hiddenInfoRecord.getPreventionCheckTaskId());
                if (!ObjectUtils.isEmpty(checkTask)){
                    hiddenInfoRecord.setPreventionCheckTask(checkTask);
                }
            }
        }
        return getDataTable(recordList);
    }


    /**
     * 导出
     * @param response
     * @param preventionHiddenRegister
     */
    @Log(title = "隐患清单(", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PreventionHiddenRegister preventionHiddenRegister){
        List<PreventionHiddenRegister> list = preventionHiddenRegisterService.queryAll(preventionHiddenRegister);
        ExcelUtil<PreventionHiddenRegister> util = new ExcelUtil<>(PreventionHiddenRegister.class);
        util.exportExcel(response, list, "隐患清单(");
    }


    /**
     * APP首页 我的隐患
     * @return
     */
    @GetMapping("/getCountApp")
    public AjaxResult getCountApp() {

        String username = SecurityUtils.getLoginUser().getUser().getNickName();

        PreventionHiddenRegister preventionHiddenRegister1 = new PreventionHiddenRegister();
        preventionHiddenRegister1.setRectificationUserName(username);
        preventionHiddenRegister1.setHiddenProgress("已超时");
        List<PreventionHiddenRegister> preventionHiddenRegisters1 = preventionHiddenRegisterService.queryByPage(preventionHiddenRegister1);

        PreventionHiddenRegister preventionHiddenRegister2 = new PreventionHiddenRegister();
        preventionHiddenRegister2.setHiddenCheckUser(username);
        preventionHiddenRegister2.setHiddenProgress("待整改");
        List<PreventionHiddenRegister> preventionHiddenRegisters2 = preventionHiddenRegisterService.queryByPage(preventionHiddenRegister2);

        PreventionHiddenRegister preventionHiddenRegister3 = new PreventionHiddenRegister();
        preventionHiddenRegister3.setRectificationUserName(username);
        preventionHiddenRegister3.setHiddenProgress("待整改");
        List<PreventionHiddenRegister> preventionHiddenRegisters3 = preventionHiddenRegisterService.queryByPage(preventionHiddenRegister3);

        PreventionHiddenRegister preventionHiddenRegister4 = new PreventionHiddenRegister();
        preventionHiddenRegister4.setRectificationUserName(username);
        preventionHiddenRegister4.setHiddenProgress("待审核");
        List<PreventionHiddenRegister> preventionHiddenRegisters4 = preventionHiddenRegisterService.queryByPage(preventionHiddenRegister4);

        PreventionHiddenRegister preventionHiddenRegister5 = new PreventionHiddenRegister();
        preventionHiddenRegister5.setRectificationUserName(username);
        preventionHiddenRegister5.setHiddenProgress("待复核");
        List<PreventionHiddenRegister> preventionHiddenRegisters5 = preventionHiddenRegisterService.queryByPage(preventionHiddenRegister5);

        List<PreventionHiddenRegister> preventionHiddenRegisters6 = preventionHiddenRegisterService.queryByPage(new PreventionHiddenRegister());

        Map<String,Integer> map = new HashMap<>();
        map.put("wei", CollUtil.isEmpty(preventionHiddenRegisters2) ? 0 : preventionHiddenRegisters2.size());
        map.put("chao", CollUtil.isEmpty(preventionHiddenRegisters1) ? 0 : preventionHiddenRegisters1.size());
        map.put("dai", CollUtil.isEmpty(preventionHiddenRegisters3) ? 0 : preventionHiddenRegisters3.size());
        map.put("shen", CollUtil.isEmpty(preventionHiddenRegisters4) ? 0 : preventionHiddenRegisters4.size());
        map.put("fu", CollUtil.isEmpty(preventionHiddenRegisters5) ? 0 : preventionHiddenRegisters5.size());
        map.put("zong", CollUtil.isEmpty(preventionHiddenRegisters6) ? 0 : preventionHiddenRegisters6.size());
        return AjaxResult.success(map);
    }

}

